package com.rfid.a252robot.admin;

import android.app.AlarmManager;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.text.TextUtils;
import android.widget.Toast;

import androidx.annotation.Nullable;

import com.rfid.common.log.LogUtils;
import com.rfid.mqtt.MqttManager;
import com.rfid.util.PreferenceUtil;
import com.spectre.generate.ConfigManager;

import java.util.Calendar;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

public class DailyWorkService extends Service {


    ScheduledExecutorService mStartService = Executors.newSingleThreadScheduledExecutor();
    ScheduledExecutorService mEndService = Executors.newSingleThreadScheduledExecutor();
    ScheduledFuture mScheduledFuture1,mScheduledFuture2;
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        LogUtils.v("DailyWorkService onCreate");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        LogUtils.v("DailyWorkService onDestroy");
        stopAlarm();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        setAlarm();
        return super.onStartCommand(intent, flags, startId);
    }

    private void stopAlarm() {
        LogUtils.v("stopAlarm");
        if (mScheduledFuture1 != null) {
            mScheduledFuture1.cancel(true);
        }
        if (mScheduledFuture2 != null) {
            mScheduledFuture2.cancel(true);
        }
    }

    private long getTime(int hour, int minute) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(System.currentTimeMillis());
        calendar.set(Calendar.HOUR_OF_DAY, hour);
        calendar.set(Calendar.MINUTE, minute);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);

        // 如果当前时间已经超过设定的闹钟时间，则设置闹钟为明天的同一时间
        if (calendar.before(Calendar.getInstance())) {
            calendar.add(Calendar.DAY_OF_WEEK, 1);
        }
        return calendar.getTimeInMillis();
    }

    public void setAlarm() {
        LogUtils.v("setAlarm");
        if (mScheduledFuture1 != null) {
            mScheduledFuture1.cancel(true);
        }
        if (mScheduledFuture2 != null) {
            mScheduledFuture2.cancel(true);
        }
        int sh = PreferenceUtil.getInt("startHour",-1);
        int eh = PreferenceUtil.getInt("endHour",-1);
        int sm = PreferenceUtil.getInt("startMin",-1);
        int em = PreferenceUtil.getInt("endMin",-1);
        if (sh == -1) {
            LogUtils.v("not set Alarm!");
            return;
        }
        long st = getTime(sh,sm);
        long sdelay = st - System.currentTimeMillis();
        LogUtils.v("mStartService delay = " + sdelay/1000 + "s");
        mScheduledFuture1 = mStartService.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                LogUtils.v("scheduleAtFixedRate mStartService");
                try {
                    boolean r = MqttManager.INSTANCE.startMoveTask(true);
                    LogUtils.v("mStartService = " + r);
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                    e.printStackTrace();
                }
            }
        },sdelay, AlarmManager.INTERVAL_DAY, TimeUnit.MILLISECONDS);
        long et = getTime(eh,em);
        long edelay = et - System.currentTimeMillis();
        LogUtils.v("mEndService delay = " + edelay/1000 + "s");
        mScheduledFuture2 = mEndService.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                LogUtils.v("scheduleAtFixedRate mEndService");
                String mapCode = ConfigManager.INSTANCE.getChargeConfig().getMapCode();
                String pointName = ConfigManager.INSTANCE.getChargeConfig().getPointName();
                if (TextUtils.isEmpty(mapCode) || TextUtils.isEmpty(pointName)) {
                    return;
                }
                MqttManager.INSTANCE.cancelTask(true);
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                MqttManager.INSTANCE.sendCharge(mapCode,pointName);
            }
        },edelay, AlarmManager.INTERVAL_DAY, TimeUnit.MILLISECONDS);
    }
}
